package br.brpv.silvestrin.conferencia.webservice;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.ksoap2.serialization.SoapObject;

import android.content.Context;
import br.brpv.silvestrin.conferencia.R;
import br.brpv.silvestrin.conferencia.helper.Compression;
import br.brpv.silvestrin.conferencia.models.Company;
import br.brpv.silvestrin.conferencia.models.User;
import br.brpv.silvestrin.conferencia.webservice.LoginWebservice.LoginwebserviceListener;
import br.brpv.silvestrin.conferencia.webservice.WebserviceManager.WSRequestCompleteListener;

public class CompanyWebService extends Webservice
		{

	CompanyWebServiceListener companyWebServiceListener;

	public CompanyWebService(Context context,
			CompanyWebServiceListener companyWebServiceListener) {
		super(context);

		this.companyWebServiceListener = companyWebServiceListener;
	}

	public void getCompaniesList() {
		WebserviceManager ws = new WebserviceManager(context,
				context.getString(R.string.wsmessage_getCompaniesList), new CompanyListResultListener());

		try {
			String wlParametros = "" + "p_filtro|varchar|||";

			ws.execute(WebserviceManager.Method.F_GET_PACKAGE,
					"f3i_col_silvestrin.prc_busca_empresas", wlParametros);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private class CompanyListResultListener implements WSRequestCompleteListener<SoapObject> {		
		public void onTaskComplete(SoapObject result) {
			if (result == null) {
				// TODO avisar que nao conseguiu acessar o servidor
				companyWebServiceListener.onGetCompaniesListError();
			} else {
	
				String resultString = Compression.decompress(result.getProperty(0)
						.toString());
				
				companyWebServiceListener.onGetCompaniesListResult(parseCompanyList(resultString));
			}
		}		
	}
	
	private ArrayList<Company> parseCompanyList(String result) {
		StringTokenizer row = new StringTokenizer(result,
				Character.toString(ROW_BREAK_CHARACTER));
		ArrayList<Company> companyArrayList = new ArrayList<Company>();
		// pula primeira linha
		if (row.countTokens() != 0) {
			row.nextToken();
			while (row.hasMoreTokens()) {

				ArrayList<String> tokens = new ArrayList<String>();
				String str = row.nextToken();

				while (str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
					tokens.add(str.substring(0,
							str.indexOf(COLUMN_BREAK_CHARACTER)));
					str = str
							.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
				}
				tokens.add(str);

				companyArrayList.add(new Company(tokens.get(0), tokens
						.get(1), tokens.get(2), tokens.get(3)));
			}
		}
		
		return companyArrayList;
	}
	
	public void getDefaultCompany(String userId) {
        WebserviceManager ws = new WebserviceManager(context, context.getString(R.string.wsmessage_getCompaniesList),
                new GetDefaultCompanyListener());

        try {
            String wlParametros = "" +
                    "p_usuarioid|number|"+ new Integer(userId) + "||";

            ws.execute(WebserviceManager.Method.F_GET_VALOR_PACKAGE, "pkg_sil_usu_empr_default.prc_retorna_empresa_default", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class GetDefaultCompanyListener implements WSRequestCompleteListener<SoapObject> {
       
        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                //TODO avisar que nao conseguiu acessar o servidor
                companyWebServiceListener.onGetDefaultCompanyError();
            } else {
                String resultString = result.getProperty(0).toString();
                companyWebServiceListener.onGetDefaultCompanyResult(resultString);
            }

        }
    }
    
	public interface CompanyWebServiceListener {
		public void onGetCompaniesListError();
		public void onGetCompaniesListResult(ArrayList<Company> companyArrayList);
		
		public void onGetDefaultCompanyError();
		public void onGetDefaultCompanyResult(String companyId);		
	}
}
